"""
@Author  : 康帅
@Time    : 2021/3/23 15:24
@Function: 组合模式：遍历文件夹下的文件及文件大小
"""
import os

from DesignMode.CombinationMode.ComposeBase import Component, Composite


class FileDetail(Component):
    """ 文件详情 """

    def __init__(self, name):
        super().__init__(name)
        self._size = 0

    def set_size(self, size):
        self._size = size

    def get_file_size(self):
        return self._size

    def feature(self, indent):
        # 文件大小，单位KB,精确度：2位小数
        file_size = round(self._size / float(1024), 2)
        print(f"文件名称：{self._name},文件大小：{file_size}")


class FolderDetail(Composite):
    """ 文件夹详情 """

    def __init__(self, name):
        super().__init__(name)
        self._count = 0

    def set_count(self, count):
        self._count = count

    def get_count(self):
        return self._count

    def feature(self, indent):
        print(f"文件夹名：{self._name}，文件数量：{self._count}，包含文件：{super().feature(indent)}")


def scan_dir(root_path, folder_detail):
    """ 扫描某一文件夹下的目录 """

    if not os.path.isdir(root_path):
        raise ValueError(f"root_path不是有效的路径{root_path}")

    if folder_detail is None:
        raise ValueError("folder_detail不能为空")

    file_names = os.listdir(root_path)
    for file_name in file_names:
        file_path = os.path.join(root_path, file_name)
        if os.path.isdir(file_path):
            folder = FolderDetail(file_name)
            scan_dir(file_path, folder)
            folder_detail.add_components(folder)
        else:
            file_detail = FileDetail(file_name)
            file_detail.set_size(os.path.getsize(file_path))
            folder_detail.add_components(file_detail)
            folder_detail.set_count(folder_detail.get_count() + 1)


if __name__ == '__main__':
    folder = FolderDetail("python设计模式")
    scan_dir("C:\python设计模式", folder)
    folder.feature("")
